package com.coder306.shiro;

import com.coder306.bean.UpmsPermission;
import com.coder306.bean.UpmsRole;
import com.coder306.bean.UpmsUser;
import com.coder306.service.UpmsPermissionService;
import com.coder306.service.UpmsUserService;

import java.util.List;

import javax.security.auth.Subject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UpmsRealm extends AuthorizingRealm{

    @Autowired
    private UpmsUserService upmsUserService;
    
    @Autowired
    private UpmsPermissionService upmsPermissionService;

    /**
     * 获取授权信息
     * @param principals
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	
    	org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
    	String username = (String)subject.getPrincipal();
    	UpmsUser upmsUser = upmsUserService.queryByUserName(username);
    	
    	
    	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    	
    	List<UpmsRole> roles = upmsPermissionService.queryRoleByUserId(upmsUser.getUserId());
    	if(roles!=null) {
    		for(UpmsRole r : roles) {
    			info.addRole(r.getRoleName());
    		}
    	}
    	
    	List<UpmsPermission> permissions = upmsPermissionService.queryPermissionByUserId(upmsUser.getUserId());
    	if(permissions!=null) {
    		for(UpmsPermission p : permissions) {
    			/*
    			 * sys:*
    			 * sys:user
    			 */
    			info.addObjectPermission(new WildcardPermission(p.getPermissionValue()));
    		}
    	}
    	
        return info;
    }

    /**
     * 获取认证信息
     * @param token
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String)token.getPrincipal();
        UpmsUser upmsUser = upmsUserService.queryByUserName(username);

        return new SimpleAuthenticationInfo(upmsUser.getUserName(),upmsUser.getPassword(),getName());
    }

}
